/*******************************************************************************
 * Copyright 2011-2012 Dik Grapendaal
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package sh.grapendaal.tsuushin;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;

import org.slf4j.LoggerFactory;

/**
 * Proxy class to redirect any OutputStream to a logging call.
 */
public abstract class LogStream extends ByteArrayOutputStream {
	/**
	 * {@inheritDoc}
	 */
	@Override
	public void flush() throws IOException {
		synchronized (this) {
			super.flush();
			String line = this.toString();
			super.reset();

			if (line.trim().length() > 0) {
				log(line);
			}
		}
	}

	/**
	 * This method implements the actual logging call.
	 * 
	 * @param line
	 *            The line we received from one of the write() methods.
	 */
	protected abstract void log(String line);

	/**
	 * Sets up System.out and System.err so that those are actually calls to our
	 * logging mechanism. System.out are logged with level info, System.err are
	 * logged with level error.
	 */
	static void setupLogger() {
		System.setOut(new PrintStream(new LogStream() {
			@Override
			protected void log(String line) {
				LoggerFactory.getLogger("stdout").info(line);
			}
		}, true));
		System.setErr(new PrintStream(new LogStream() {
			@Override
			protected void log(String line) {
				LoggerFactory.getLogger("stderr").error(line);
			}
		}, true));
	}
}
